package com.jimmy.tx.service.impl;

import com.jimmy.tx.dao.UserDao;
import com.jimmy.tx.service.UserService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @version 1.0
 * @ ClassName UserServiceImpl
 * <p> TODO
 * @ author JIMMY
 * @ Date 2020/11/5 0005 下午 8:40
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    //编程式使用的事务模板对象
    //注入事务模板类对象
    private TransactionTemplate template;

    public void setTemplate(TransactionTemplate template) {
        this.template = template;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    /**
     * 没有事务
     * @param from
     * @param to
     * @param money
     */
    public void transfer(String from, String to, Double money) {
        userDao.outMoney(from,money);
//        int i = 1/0;
        userDao.inMoney(to,money);
    }


    /**
     * 编程式事务(该方式每个方法都要写SPRING团队用了AOP做了通知可以参考XML配置2)
     * @param out
     * @param in
     * @param money
     */
	public void transferTrancation(final String out, final String in, final Double money) {
		//声明一个事务回滚的对象
		TransactionCallback tc = new TransactionCallbackWithoutResult() {
			//控制事务回滚的
			protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                userDao.outMoney(out, money);
				int i = 1/0;
                userDao.inMoney(in, money);
			}
		};
		template.execute(tc);
	}

}
